package com.foreveredu.propms.web.struts.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.*;
import jxl.write.*;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.taglibs.standard.extra.spath.Path;

import com.foreveredu.propms.domain.District;
import com.foreveredu.propms.domain.House;
import com.foreveredu.propms.domain.Role;
import com.foreveredu.propms.domain.SubDistrict;
import com.foreveredu.propms.domain.User;
import com.foreveredu.propms.service.IManagementService;
import com.foreveredu.propms.web.struts.actionform.SubDistrictActionForm;

public class SubDistrictAction extends AbstractBaseDispatchAction {

	private IManagementService managementService = null;

	public IManagementService getManagementService() {
		return managementService;
	}

	public void setManagementService(IManagementService managementService) {
		this.managementService = managementService;
	}

	// 跳转到小区管理列表页面
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 获取当前登录用户
		User user = null;
		try {
			user = managementService.findUserByUsername(this.getPrincipal()
					.getUsername());
		} catch (ClassCastException e) {
			// 用户长时间不操作，session丢失后，跳转到登录页面
			return mapping.findForward("login");
		}
		Set<Role> roles = user.getRoles();
		Role role_Admin = managementService.findRoleByName("ADMIN");
		Role role_ChargeMan = managementService.findRoleByName("CHARGEMAN");

		List<SubDistrict> subDistrictList = null;
		if (roles.contains(role_Admin)) {
			subDistrictList = managementService.findSubDistricts();
		} else if (roles.contains(role_ChargeMan)) {
			// 获取当前物业管理员所在的物业服务处
			District dis = user.getDistrict();
			subDistrictList = managementService.findSubDistrictsOfDistrict(dis);
		}

		request.setAttribute("subDistrictList", subDistrictList);

		return mapping.findForward("list");
	}

	// 跳转到小区添加页面
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		// 获取当前登录用户
		User user = null;
		try {
			user = managementService.findUserByUsername(this.getPrincipal()
					.getUsername());
		} catch (ClassCastException e) {
			// 用户长时间不操作，session丢失后，跳转到登录页面
			return mapping.findForward("login");
		}
		Set<Role> roles = user.getRoles();
		Role role_Admin = managementService.findRoleByName("ADMIN");
		Role role_ChargeMan = managementService.findRoleByName("CHARGEMAN");

		List<District> districtList = null;
		if (roles.contains(role_Admin)) {
			districtList = managementService.findDistricts();
		} else if (roles.contains(role_ChargeMan)) {
			// 获取当前物业管理员所在的物业服务处
			District dis = user.getDistrict();
			districtList = new ArrayList<District>();
			districtList.add(dis);
		}

		request.setAttribute("districtList", districtList);

		return mapping.findForward("add");
	}

	// 完成到小区添加操作
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		SubDistrictActionForm sdaf = (SubDistrictActionForm) form;

		// 表单校验、
		if (sdaf.getSubDistrictId() == null
				|| "".equals(sdaf.getSubDistrictId())) {
			request.setAttribute("subDistrictIdError", "请输入小区编号");

			return mapping.findForward("toAdd");
		} else if (managementService.findSubDistrictBySubDistrictId(sdaf
				.getSubDistrictId()) != null) {
			request.setAttribute("subDistrictIdRequest", "您输入的小区编号已存在，请重新输入！");

			return mapping.findForward("toAdd");
		}
		if (sdaf.getName() == null || "".equals(sdaf.getName())) {
			request.setAttribute("subDistrictNameError", "请输入小区名称");

			return mapping.findForward("toAdd");
		}
		if (sdaf.getAddress() == null || "".equals(sdaf.getAddress())) {
			request.setAttribute("subDistrictAddressError", "请输入小区地址");

			return mapping.findForward("toAdd");
		}
		if (sdaf.getTakeTime() == null || "".equals(sdaf.getTakeTime())) {
			request.setAttribute("subDistrictTakeTimeError", "请输入接管年份");

			return mapping.findForward("toAdd");
		}
		if (sdaf.getDistrictId() == 0) {
			request.setAttribute("districtIdError", "请输入所属管理区！");

			return mapping.findForward("toAdd");
		}

		SubDistrict subDistrict = new SubDistrict();
		PropertyUtils.copyProperties(subDistrict, sdaf);

		District district = managementService.findDistrictById(sdaf
				.getDistrictId());
		subDistrict.setDistrict(district);

		managementService.saveSubDistrict(subDistrict);

		return mapping.findForward("toList");
	}

	// 跳转到小区修改页面
	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		SubDistrictActionForm sdaf = (SubDistrictActionForm) form;
		SubDistrict subDistrict = managementService.findSubDistrictById(sdaf
				.getId());
		request.setAttribute("subDistrict", subDistrict);

		// 将默认值保存到ActionForm中，以便在JSP表单中显示该值。
		sdaf.setDistrictId(subDistrict.getDistrict().getId());

		// 获取当前登录用户
		User user = null;
		try {
			user = managementService.findUserByUsername(this.getPrincipal()
					.getUsername());
		} catch (ClassCastException e) {
			// 用户长时间不操作，session丢失后，跳转到登录页面
			return mapping.findForward("login");
		}
		Set<Role> roles = user.getRoles();
		Role role_Admin = managementService.findRoleByName("ADMIN");
		Role role_ChargeMan = managementService.findRoleByName("CHARGEMAN");

		List<District> districtList = null;
		if (roles.contains(role_Admin)) {
			districtList = managementService.findDistricts();
		} else if (roles.contains(role_ChargeMan)) {
			// 获取当前物业管理员所在的物业服务处
			District dis = user.getDistrict();
			districtList = new ArrayList<District>();
			districtList.add(dis);
		}

		request.setAttribute("districtList", districtList);

		return mapping.findForward("update");
	}

	// 保存小区修改数据
	public ActionForward updateSave(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		SubDistrictActionForm sdaf = (SubDistrictActionForm) form;

		// 添加校验功能
		if (!sdaf.getSubDistrictId().equals(
				managementService.findSubDistrictById(sdaf.getId())
						.getSubDistrictId())) {// 校验提交的小区编码是否修改

			if (sdaf.getSubDistrictId() == null
					|| "".equals(sdaf.getSubDistrictId())) {
				request.setAttribute("subDistrictIdError", "请输入小区编号");

				return mapping.findForward("toUpdate");
			} else if (managementService.findSubDistrictBySubDistrictId(sdaf
					.getSubDistrictId()) != null) {
				request.setAttribute("subDistrictIdRequest",
						"您输入的小区编号已存在，请重新输入！");

				return mapping.findForward("toUpdate");
			}
		}
		if (sdaf.getName() == null || "".equals(sdaf.getName())) {
			request.setAttribute("subDistrictNameError", "请输入小区名称");

			return mapping.findForward("toUpdate");
		}
		if (sdaf.getAddress() == null || "".equals(sdaf.getAddress())) {
			request.setAttribute("subDistrictAddressError", "请输入小区地址");

			return mapping.findForward("toUpdate");
		}
		if (sdaf.getTakeTime() == null || "".equals(sdaf.getTakeTime())) {
			request.setAttribute("subDistrictTakeTimeError", "请输入接管年份");

			return mapping.findForward("toUpdate");
		}
		if (sdaf.getDistrictId() == 0) {
			request.setAttribute("districtIdError", "请输入所属管理区！");

			return mapping.findForward("toUpdate");
		}

		SubDistrict subDistrict = managementService.findSubDistrictById(sdaf
				.getId());
		PropertyUtils.copyProperties(subDistrict, sdaf);
		District district = managementService.findDistrictById(sdaf
				.getDistrictId());
		subDistrict.setDistrict(district);
		managementService.updateSubDistrict(subDistrict);

		return mapping.findForward("updateSave");
	}

	// 完成小区删除操作
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		SubDistrictActionForm sdaf = (SubDistrictActionForm) form;
		managementService.deleteSubDistrictById(sdaf.getId());

		return mapping.findForward("del");
	}

	public ActionForward writeDBToXLS(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {

			SubDistrictActionForm sdaf = (SubDistrictActionForm) form;
			SubDistrict subDistrict = managementService.findSubDistrictById(sdaf.getId());
			// 读取数据库中所有报名记录
			List<House> houses = managementService.findAllHousesBySubDistrict(subDistrict);

			String fileName = subDistrict.getName() + "业主水电报表";

			String path = this.toExcel(houses, fileName, response, request);

			response.setContentType("application/octet-stream;charset=UTF-8");
			response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xls");
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path));
			ServletOutputStream sos = response.getOutputStream();
			BufferedOutputStream bos = new BufferedOutputStream(sos);
			byte[] buffer = new byte[1024];
			int len = -1;
			while ((len = bis.read(buffer)) != -1) {
				bos.write(buffer, 0, len);
			}
			bos.close();
			sos.close();
			bis.close();
			//删除文件
			File file = new File(path);
			if (file != null) {
				file.delete();
			}
			
		} catch (Exception e) {
			log.error("请求出错", e);
		}
		return null;
	}

	@SuppressWarnings("deprecation")
	private String toExcel(List<House> houses, String fileName,
			HttpServletResponse response, HttpServletRequest request) {
		// 使用jxl导出excle
		String path = request.getSession().getServletContext().getRealPath("")+ fileName + ".xls";
		try {
			File file = new File(path);
			WritableWorkbook wwb = Workbook.createWorkbook(file);
			WritableSheet ws = wwb.createSheet("业主水电报表", 0);

			/*********** 设置列宽 *****************/
			ws.setColumnView(0, 15); // 第1列
			ws.setColumnView(1, 15); // 第2列
			ws.setColumnView(2, 15);// 第3列
			ws.setColumnView(3, 15); // 第4列
			ws.setColumnView(4, 15); // 第5列
			ws.setColumnView(5, 15); // 第6列
			ws.setColumnView(6, 15); // 第7列
			ws.setColumnView(7, 15); // 第8列
			ws.setColumnView(8, 15); // 第9列
			ws.setColumnView(9, 15); // 第10列

			/***************** 设置单元格字体 ***************/
			// 字体
			WritableFont NormalFont = new WritableFont(WritableFont.ARIAL, 10);
			WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 18,
					WritableFont.BOLD);
			WritableFont tableFont = new WritableFont(WritableFont.ARIAL, 12,
					WritableFont.NO_BOLD);
			WritableFont baodanFont = new WritableFont(WritableFont.ARIAL, 10,
					WritableFont.BOLD);

			/***************** 以下设置几种格式的单元格 *************/
			// 用于标题
			WritableCellFormat wcf_title = new WritableCellFormat(BoldFont);
			wcf_title.setBorder(Border.NONE, BorderLineStyle.THIN); // 线条
			wcf_title.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直对齐
			wcf_title.setAlignment(Alignment.CENTRE); // 水平对齐
			wcf_title.setWrap(true); // 是否换行

			// 用于表格标题
			WritableCellFormat wcf_tabletitle = new WritableCellFormat(
					tableFont);
			wcf_tabletitle.setBorder(Border.NONE, BorderLineStyle.THIN); // 线条
			wcf_tabletitle.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直对齐
			wcf_tabletitle.setAlignment(Alignment.CENTRE); // 水平对齐
			wcf_tabletitle.setWrap(true); // 是否换行

			// 用于正文左
			WritableCellFormat wcf_left = new WritableCellFormat(NormalFont);
			wcf_left.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
			wcf_left.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直对齐
			wcf_left.setAlignment(Alignment.LEFT);
			wcf_left.setWrap(true); // 是否换行

			// 用于正文左
			WritableCellFormat wcf_center = new WritableCellFormat(NormalFont);
			wcf_center.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
			wcf_center.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直对齐
			wcf_center.setAlignment(Alignment.CENTRE);
			wcf_center.setWrap(true); // 是否换行

			// 用于正文右
			WritableCellFormat wcf_right = new WritableCellFormat(NormalFont);
			wcf_right.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
			wcf_right.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直对齐
			wcf_right.setAlignment(Alignment.RIGHT);
			wcf_right.setWrap(false); // 是否换行

			// 用于跨行
			WritableCellFormat wcf_merge = new WritableCellFormat(NormalFont);
			wcf_merge.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
			wcf_merge.setVerticalAlignment(VerticalAlignment.TOP); // 垂直对齐
			wcf_merge.setAlignment(Alignment.LEFT);
			wcf_merge.setWrap(true); // 是否换行

			WritableCellFormat wcf_table = new WritableCellFormat(NormalFont);
			wcf_table.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
			wcf_table.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直对齐
			wcf_table.setAlignment(Alignment.CENTRE);
			wcf_table.setBackground(Colour.GRAY_25);
			wcf_table.setWrap(true); // 是否换行

			/** */
			/** ************单元格格式设置完成****************** */

			// 表格标题
			ws.addCell(new Label(0, 0, "房产编号", wcf_tabletitle));
			ws.addCell(new Label(1, 0, "业主姓名", wcf_tabletitle));
			ws.addCell(new Label(2, 0, "电表1起码", wcf_tabletitle));
			ws.addCell(new Label(3, 0, "电表1止码", wcf_tabletitle));
			ws.addCell(new Label(4, 0, "电表2起码", wcf_tabletitle));
			ws.addCell(new Label(5, 0, "电表2止码", wcf_tabletitle));
			ws.addCell(new Label(6, 0, "水表1起码", wcf_tabletitle));
			ws.addCell(new Label(7, 0, "水表1止码", wcf_tabletitle));
			ws.addCell(new Label(8, 0, "水表2起码", wcf_tabletitle));
			ws.addCell(new Label(9, 0, "水表2止码", wcf_tabletitle));

			// 读取数据库中所有报名记录
			int line = 1;

			for (Iterator<House> houseIter = houses.iterator(); houseIter
					.hasNext();) {
				House house = houseIter.next();
				ws.addCell(new Label(0, line, house.getHouseId()));
				ws.addCell(new Label(1, line, house.getOwner().getName()));
				line++;
			}

			wwb.write();// 将数据写入EXCEL文档
			wwb.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return path;

		// 导出excle方法2（最简单）
		/*
		 * try { // 对文件名作处理，避免中文乱码问题
		 * 
		 * // 设置response相应属性，设置为下载 response.setCharacterEncoding("utf-8");
		 * response.setContentType("application/x-msdownload");
		 * response.setHeader("Content-Disposition", "attachment;filename=" +
		 * fileName); // 获得response中的输出 OutputStream out =
		 * response.getOutputStream(); // excel表格第一行标题，本例中不采用poi或jxl，只对每个单元属性后面添
		 * // 加\t，每行结束加\n 。这是excel文件的基本属性。 String head =
		 * "房产编号\t业主姓名\t电表1起码\t电表1止码\t电表2起码\t电表2止码\t水表1起码\t水表1止码\t水表2起码\t水表2止码\n"
		 * ; // 编码应该根据本地编码来确定。如果是台湾同胞，这里需要改为 big5 out.write(head.getBytes());
		 * for (House h : houses) { // 加上\t,\n
		 * 等分隔符，写出文件，当文件以.xl命名时，打开即为普通excel文件
		 * 
		 * String s = "\'"+h.getHouseId() + "\t" + h.getOwner().getName() +
		 * "\n"; out.write(s.getBytes()); } out.flush(); out.close(); } catch
		 * (IOException e) { e.printStackTrace(); }
		 */

	}
}
